<template>
  <div class="container">
    <!-- 弹框 -->
    <el-dialog :title="form.addDate? '修改目录' : '新增目录'" :visible="directorysTrue" @open='onOpen'  @close="close" width="30%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属学科" v-if="id ? false : true" >
          <el-select v-model="form.subjectID" placeholder="请选择">
            <el-option
              v-for="item in simpleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="form.directoryName" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { add, update } from '@/api/hmmm/directorys'
export default {
  model: {
    prop: 'directorysTrue'
  },
  props: {
    directorysTrue: {
      type: Boolean,
      required: true
    },
    row: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      form: {
        subjectID: '',
        directoryName: ''
      },
      rules: {
        directoryName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      simpleList: [],
      id: this.$route.query.id // 传参过来的id
    }
  },
  created () {
    this.getSimple()
  },
  methods: {
    // 获取简单数据列表
    async getSimple () {
      const res = await simple()
      this.simpleList = res.data
    },
    // 新增目录 编辑目录
    async onSave () {
      await this.$refs.form.validate()
      try {
        if (this.form.addDate) {
          await update(this.form)
          this.$message.success('编辑成功')
        } else {
          await add({ directoryName: this.form.directoryName, subjectID: (this.form.subjectID - 0) })
          this.$message.success('添加成功')
        }

        this.$emit('result')
        this.close()
      } catch (error) {
        console.dir(error)
      }
    },
    // 关闭弹窗
    close () {
      this.form = {}
      this.$emit('input', false)
      this.$emit('close')
    },
    onOpen () {
      if (this.id) {
        this.form.subjectID = this.id
      }
      if (this.row.addDate) {
        this.form = this.row
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
